/*==========================================================
 *
 * @author	Limpo, limpo_soft@qq.com
 * @date	10/30/11 09:28:57 CST
 * @brief	
 *
 *  Copyright (c) 2011, Limpo
 *========================================================== 
 */

#include "log.h"
#include "ctime.h"
#include <stdarg.h>
#include <sstream>

#define MAX_BUFF 2048
#define FILE_FORMAT "%Y%m%d-%H"
#define DATE_FORMAT "%Y/%m/%d %H:%M:%S"
#define ENABLE_LOG

Oxygen::Log g_logger;

namespace Oxygen
{
	Log::Log()
		: m_file( NULL )
	{
		OnInit();
	}

	Log::~Log()
	{
		if( m_file )
			fclose( m_file );

		m_file = NULL;
	}

	void Log::OnInit()
	{
		// change str buff to [MAX_BUFF] byte
		m_buff.reserve( MAX_BUFF );
		m_buff.resize( MAX_BUFF );

		if( !FlushName() )
		{
			printf( "Init log file to falied! %s\n", m_name.c_str() );
			return ;
		}

		SaveToFile( "\n===============[Server is starting on %s]==============", Time::Format() );
		SaveToFile( "File: %s", m_name.c_str() );
	}

	bool Log::FlushName()
	{
		std::stringstream str;
		str << "log_" << Oxygen::Time::Format( FILE_FORMAT ) << ".log";

		if( m_name.empty() || m_name != str.str() )
		{
			m_name = str.str();
			FlushFile();
		}

		return m_file != NULL;
	}
	
	void Log::FlushFile()
	{
		if( m_file )
		{
			fflush( m_file );
			fclose( m_file );
		}

		m_file = fopen( m_name.c_str(), "a+" );

		if( !m_file )
		{
			printf( "Init log file to falied! %s", m_name.c_str() );
			return ;
		}
		
		SaveToFile( "******[Switching log file to %s]******", m_name.c_str() );
	}

	void Log::SaveToFile( const char* log, ... )
	{
		assert( m_file && "FILE ptr is NULL" );
		
		FMT_STRING( &m_buff[0], m_buff.size(), log );
		
		fprintf( m_file, "[%s]: %s\n", Time::Format( DATE_FORMAT ), &m_buff[0] );
		fflush( m_file );
	}
	
	void print( BackColor bcolor, ForeColor fcolor, LightType light, const char *fmt, ... )
	{
		static char buff[MAX_BUFF] = { '\0' };
		bzero( buff, sizeof( buff ) );
	
		FMT_STRING( buff, sizeof( buff ), fmt );

		printf( "\033[%u;%um\033[%dm", bcolor, fcolor, light );
		printf( "\033[%u;%um%s\033[0m\n", bcolor, fcolor, buff );

#ifdef ENABLE_LOG
		g_logger.SaveToFile( buff );
#endif
	}

}; // end of Oxygen
